package com.hqyj.fj.javaSpringBoot.listener;



import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@WebListener
public class LogDestroyListener implements ServletContextListener {

   private final static Logger LOGGER = LoggerFactory.getLogger(LogDestroyListener.class);

   @Override
   public void contextInitialized(ServletContextEvent sce) {
      LOGGER.debug("==== Init Context ====");

      File destFolder = new File("/log");
      if (destFolder == null || !destFolder.exists()) {
         return;
      }

      DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
      String currentDate = dtf.format(LocalDateTime.now());

      File[] files = destFolder.listFiles();
      for (File file : files) {
         String fileName = file.getName();
         if (!fileName.contains(currentDate)) {
            file.delete();
         }
      }
   }

   @Override
   public void contextDestroyed(ServletContextEvent sce) {
      LOGGER.debug("==== Destroy Context ====");
   }
}
